package com.techsoul.common.core.util.lang;

import java.text.DecimalFormat;

public class MoneyUtils {
    public static String convertTo(double src) {
        final String units[] = {"分", "角", "元", "拾", "佰", "仟",
                "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾", "佰", "仟"};
        final String numbers[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

        String result = "";

        src = src * 100;
        DecimalFormat df = new DecimalFormat("#");
        String temp = df.format(src);

        for (int i = 1; i <= temp.length(); i++) {
            result = result + numbers[temp.charAt(i - 1) - 48];
            result = result + units[temp.length() - i];
        }

        result = replaceAll(result, "零分", "零");
        result = replaceAll(result, "零角", "零");
        result = replaceAll(result, "零拾", "零");
        result = replaceAll(result, "零佰", "零");
        result = replaceAll(result, "零仟", "零");

        result = replaceAll(result, "零元", "元");
        result = replaceAll(result, "零万", "万");
        result = replaceAll(result, "零亿", "亿");
        result = replaceAll(result, "零兆", "兆");

        result = replaceAll(result, "零零", "零");

        if (result.substring(result.length() - 1).equals("零"))
            result = result.substring(0, result.length() - 1);

        if (result.substring(result.length() - 1).equals("元") || result.substring(result.length() - 1).equals("角"))
            result = result + "整";

        return result;
    }

    public static String replaceAll(String src, String replacedSrc, String newSrc) {
        while (src.indexOf(replacedSrc) > 0) {
            src = src.replaceAll(replacedSrc, newSrc);
        }
        return src;
    }
}
